package android.gpstrac.data;

/**
 * A response from the server.
 *
 * @author Nicolas Papin
 */
public class ServerResponse implements Transmittable
{
	public enum ResponseType
	{
		REQ_OK,
		REQ_INVALID,
		USER_INVALID,
		SERV_ERR;
		
		static public ResponseType fromOrdinal(int ord)
		{
			ResponseType ords[] = ResponseType.values();
			
			for(int i = 0; i < ords.length; i++)
			{
				if(ords[i].ordinal() == ord)
					return ords[i];
			}
			
			return null;
		}
	};
	
	//
	// CLASS AND INSTANCE DATA
	//
	/**
	 * The type
	 */
	private ResponseType mType;
	
	/**
	 * The length
	 */
	private int mLen;
	
	/**
	 * Server response expected length.
	 */
	public static final int RESPONSE_LEN = 8;
	
	
	//
	// CTOR
	//
	public ServerResponse(ResponseType type, int len)
	{
		mType = type;
		mLen = len;
	}
	
	public ServerResponse()
	{
		this(null, 0);
	}
	
	//
	// METHODS
	//
	/* (non-Javadoc)
	 * @see android.gpstrac.data.Transmittable#getServerRepresentation()
	 */
	@Override
	public byte[] getServerRepresentation()
	{        
        int type = mType.ordinal();
		
        byte data[] = new byte[]
		{
			(byte)(type >>> 24), (byte)(type >>> 16), (byte)(type >>> 8), (byte)type,
			(byte)(mLen >>> 24), (byte)(mLen >>> 16), (byte)(mLen >>> 8), (byte)mLen	
		};
		
		return data;
	}

	/* (non-Javadoc)
	 * @see android.gpstrac.data.Transmittable#fillWithTransmittedData(java.lang.Byte[])
	 */
	@Override
	public void fillWithTransmittedData(byte[] data)
	{
		if(data.length < 8)
			return;
		
		if(data.length < 8)
			return;
		
		int type = (data[0] << 24) + ((data[1] & 0xFF) << 16) + ((data[2] & 0xFF) << 8) + (data[3] & 0xFF);
		mType = ResponseType.fromOrdinal(type);
		mLen = (data[4] << 24) + ((data[5] & 0xFF) << 16) + ((data[6] & 0xFF) << 8) + (data[7] & 0xFF);
	}
	
	public ResponseType getType()
	{
		return mType;
	}
	
	public int getLen()
	{
		return mLen;
	}
}
